
from fastapi import FastAPI, File, Form, UploadFile, HTTPException
from fastapi.responses import FileResponse
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import os
import uuid
import asyncio
from typing import Optional
import aiofiles

from services.video_generator import VideoGenerator
from services.task_manager import TaskManager

app = FastAPI(title="AI数字主播短视频生成器", version="1.0.0")

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 初始化服务
video_generator = VideoGenerator()
task_manager = TaskManager()

# 创建必要的目录
os.makedirs("uploads/photos", exist_ok=True)
os.makedirs("uploads/videos", exist_ok=True)
os.makedirs("temp", exist_ok=True)

@app.post("/api/upload/photo")
async def upload_photo(file: UploadFile = File(...)):
    """上传主播照片"""
    if not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="只能上传图片文件")
    
    file_extension = file.filename.split(".")[-1]
    filename = f"{uuid.uuid4()}.{file_extension}"
    file_path = f"uploads/photos/{filename}"
    
    async with aiofiles.open(file_path, "wb") as f:
        content = await file.read()
        await f.write(content)
    
    return {"filename": filename, "url": f"/api/photos/{filename}"}

@app.get("/api/photos/{filename}")
async def get_photo(filename: str):
    """获取上传的照片"""
    file_path = f"uploads/photos/{filename}"
    if os.path.exists(file_path):
        return FileResponse(file_path)
    raise HTTPException(status_code=404, detail="照片不存在")

@app.post("/api/generate")
async def generate_video(
    photo: str = Form(...),
    script: str = Form(...),
    voice: str = Form("female"),
    speed: float = Form(1.0),
    resolution: str = Form("1080x1920"),
    duration: int = Form(15)
):
    """生成短视频"""
    task_id = str(uuid.uuid4())
    
    # 创建任务
    task_data = {
        "task_id": task_id,
        "photo": photo,
        "script": script,
        "voice": voice,
        "speed": speed,
        "resolution": resolution,
        "duration": duration
    }
    
    # 添加到任务管理器
    task_manager.create_task(task_id, task_data)
    
    # 异步开始生成
    asyncio.create_task(video_generator.generate_video(task_data))
    
    return {"task_id": task_id, "status": "started"}

@app.get("/api/progress/{task_id}")
async def get_progress(task_id: str):
    """获取任务进度"""
    progress = task_manager.get_progress(task_id)
    if progress is None:
        raise HTTPException(status_code=404, detail="任务不存在")
    return progress

@app.get("/api/videos/{filename}")
async def get_video(filename: str):
    """获取生成的视频"""
    file_path = f"uploads/videos/{filename}"
    if os.path.exists(file_path):
        return FileResponse(file_path, media_type="video/mp4")
    raise HTTPException(status_code=404, detail="视频不存在")

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
